<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1500" @ok="handleSubmit">
    <a-row class="jeecg-modal-wrapper">
      <a-col :span="24" class="jeecg-modal-content">

        <BasicForm @register="registerForm" ref="formRef" name="XlCustomerOrdeForm">
          <template #storeCode="{ model, field }">
            <a-select v-model:value="model[field]" mode="tags" style="width: 100%" placeholder="请选择订单门店"
              @click="handleOpen" :default-active-first-option="false" :show-arrow="false" :filter-option="false"
              :open="false">
            </a-select>
            <!-- <a-input @click="handleOpen" v-model:value="model[field]" placeholder="请选择门店" :allowClear="true"
              /> -->
          </template>
        </BasicForm>
        <!-- 子表单区域 -->
        <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
          <a-tab-pane tab="商品列表" key="xlCustomerOrderDetail" :forceRender="true">
            <JVxeTable keep-source resizable ref="xlCustomerOrderDetail" :loading="xlCustomerOrderDetailTable.loading"
              :columns="xlCustomerOrderDetailTable.columns" :dataSource="xlCustomerOrderDetailTable.dataSource"
              :height="340" :rowNumber="true" :rowSelection="true" :disabled="formDisabled" :toolbar="true"
              @valueChange="handleValueChange" @added="addNewProduct" :cell-style="cellStyle">

              <!--商品-->
              <template #productName="{ value, row, rowIndex, column }">
                <a-input v-model:value="row['productName']" mode="tags" style="width: 100%" placeholder="请选择商品"
                  v-if="!formDisabled" @click="openOrderProductSelectModel(row, rowIndex)"
                  :default-active-first-option="false" :show-arrow="false" :filter-option="false" :open="false">
                </a-input>
                <span v-else>
                  {{ row['productName'] }}
                </span>
              </template>
            </JVxeTable>
          </a-tab-pane>
        </a-tabs>
      </a-col>

      <!-- 评论功能 -->
      <!-- <a-col :span="6" class="jeecg-comment-outer">
        <CommentPanel tableName="xl_customer_orde" :dataId="dataId" otherHeight="220"/>
      </a-col> -->
    </a-row>
    <!-- 弹窗区域 -->
    <div>
      <ProductSelModal rowKey="id" @register="registerSelModal" @getSelectResult="onSelectOrderOk"
        :customerLevel="customerLevel" :isRadioSelection="true">
      </ProductSelModal>
      <ProductSelectModel @register="ProductSelectModelRegister"></ProductSelectModel>
      <StoreInfoSelModal rowKey="id" @register="registerStoreSelModal" @getSelectResult="onSelectStoreInfoOk"
        :isRadioSelection="true">
      </StoreInfoSelModal>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTypes, JVxeColumn, JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types';
import { JVxeTable } from '/@/components/jeecg/JVxeTable'
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
import { formSchema, xlCustomerOrderDetailColumns, customerLevel } from '../XlCustomerOrde.data';
import { saveOrUpdate, xlCustomerOrderDetailList, getStoreInfoByOrderId } from '../XlCustomerOrde.api';
import { useModal } from '/@/components/Modal';
import CommentPanel from '/@/components/jeecg/comment/CommentPanel.vue';
import ProductSelModal from './ProductSelModal.vue';
import StoreInfoSelModal from './StoreInfoSelModal.vue';
import { useUserStore } from '/@/store/modules/user';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
import ProductSelectModel from './ProductSelectModel.vue';
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const formDisabled = ref(false);
const refKeys = ref(['xlCustomerOrderDetail',]);
const activeKey = ref('xlCustomerOrderDetail');
const xlCustomerOrderDetail = ref();
const tableRefs = { xlCustomerOrderDetail, };
const xlCustomerOrderDetailTable = reactive({
  loading: false,
  dataSource: [],
  columns: xlCustomerOrderDetailColumns
})

const tableRef = ref<JVxeTableInstance>();

const userStore = useUserStore();

const [registerSelModal, selModal] = useModal();
const [registerStoreSelModal, storeSelModal] = useModal();
const [ProductSelectModelRegister, ProductSelectModelOpen] = useModal();
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue,getFieldsValue , validate }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 }
});
function rowStyle({ row, rowIndex }) {
  console.log('row', row)
  console.log('rowIndex', rowIndex)
  return { 'background-color': '#FBE4D5', 'font-weight': 'bolder!important' }
}
function cellStyle({ row, column, columnIndex }) {
  if (column.field === 'aftersaleQuantity' && row.aftersaleQuantity >0 ) {
    return { 'background-color': 'red', 'font-weight': 'bolder!important' }
  }
}
const dataId = ref('1')
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  formDisabled.value = !data?.showFooter;

  if (unref(isUpdate)) {
    dataId.value = data.record?.id;  //主键id
    
    // var customerInfo = await getStoreInfoByOrderId({ orderId: data.record?.id });
    // if (!!customerInfo) {
    //   customerLevel.value = customerInfo.storeLevel;
    // }
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    //requestSubTableData(xlCustomerOrderDetailList, { id: data?.record?.id }, xlCustomerOrderDetailTable);
    requestSubTableData("/xl/xlCustomerOrde/queryNewOrderDetail", { ordercode: data.record.orderCode }, xlCustomerOrderDetailTable);

  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter })
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(requestAddOrEdit, classifyIntoFormData, tableRefs, activeKey, refKeys);

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(formDisabled) ? '编辑' : '详情'));

async function reset() {
  await resetFields();
  activeKey.value = 'xlCustomerOrderDetail';
  xlCustomerOrderDetailTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue)
  return {
    ...main, // 展开
    xlCustomerOrderDetailList: allValues.tablesValue[0].tableData,
  }
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}


const subSelIndex = ref(0)
//选择商品
async function openOrderProductSelectModel(row, rowIndex) { 
  var info = await getFieldsValue();  //当前表单数据
 
  subSelIndex.value = rowIndex;
  
  //过滤的商品
  var dataList = xlCustomerOrderDetail.value?.getTableData() || new Array();
   
  
  var filterList = new Array();
  dataList.forEach((m) => {
    filterList.push({ upcCode: m.upcCode });
  })
  
  //ProductSelectModelOpen
  selModal.openModal(true, {
    modalTitle: '选择商品',
    customerLevel: customerLevel.value,
    customerTypeCode: info.customerTypeCode,
    filterList,
  });
}

// 选择成功
async function onSelectOrderOk(options, selectList, selectRows) {
  if (selectList.length > 0) {
    //var dataList = tableRef.value?.getTableData();
    var dataList = xlCustomerOrderDetail.value?.getTableData();
    try {
      //赋值子表id
      selectRows.value.forEach((e, index) => {
        //表单赋值
        dataList[subSelIndex.value].productId = e.id;
        dataList[subSelIndex.value].productName = e.productName;
        dataList[subSelIndex.value].upcCode = e.upcCode;
        dataList[subSelIndex.value].productPrice = e.supplyPrice;
        // var data = {
        //   id: index + dataList.length,
        //   productId: e.id,
        //   productName: e.productName,
        //   productPrice: 0,
        //   producorderAmounttPrice: 0,
        // };
        // if (customerLevel.value === '一批') {
        //   dataList[subSelIndex.value].productPrice = e.l1Price
        // } else if (customerLevel.value === '二批') {
        //   dataList[subSelIndex.value].productPrice = e.l2Price
        // } else if (customerLevel.value === '三批') {
        //   dataList[subSelIndex.value].productPrice = e.l3Price
        // }

        // console.log('selectRows;', data);
        // dataList[subSelIndex.value] = data;
        // dataList.push(data);
      });
      xlCustomerOrderDetailTable.dataSource = dataList;
    } finally {
    }
  }
}


// 发送变更行请求
function handleValueChange(event) {
  let { $table, row, column } = event;
  let field = column.key;

  //结果值修改时,判定结果
  if (field === 'orderQuantity') {
    if (row['orderQuantity'] > 0 && row['productPrice'] > 0) {
      row['orderAmount'] = (row['orderQuantity'] * row['productPrice']).toFixed(2); //两位小数
    } else {
      row['orderAmount'] = '';//清空
    }

    row['isUpdate'] = '1';
    // 局部更新单元格为已保存状态
    // $table.reloadRow(row, null, field);
  }
}

async function addNewProduct(event) {
  var info = await getFieldsValue();  //当前表单数据
  //如果门店不一样了 则清空商品
  // if (!info.storeCode) {
  //   alert("请先选择订单门店,再新增商品！");
  //   const xTable = tableRef.value!.getXTable();
  //   const record = xTable.getTableData().fullData[0];
  //   tableRef.value!.removeRows(record);
  // }
  if (!info.storeCode) { 
    alert("请先选择订单门店,再新增商品！");
    xlCustomerOrderDetailTable.dataSource = [];
  }
  

}
//选择门店负责人
const handleOpen = async () => {
    storeSelModal.openModal(true, {
      modalTitle: '选择门店',
    });
};

// 选择成功
async function onSelectStoreInfoOk(options, selectList, selectRows) {
  if (selectList.length > 0) {
    try {
      var info = await getFieldsValue();  //当前表单数据
      //如果门店不一样了 则清空商品
      if(info?.storeCode != selectRows.value[0].storeCode){
        xlCustomerOrderDetailTable.dataSource = [];
      }

      //赋值表单值
      setFieldsValue({ 
        storeCode: selectRows.value[0].storeCode, 
        storeName: selectRows.value[0].storeName, 
        receiptName: selectRows.value[0].storeManager, 
        receiptPhone: selectRows.value[0].storeManagerPhone, 
        receiptZone: selectRows.value[0].province, 
        receiptAddress: selectRows.value[0].storeAddress, 
        deliveryWay: selectRows.value[0].deliveryWay, 
        deliveryType: selectRows.value[0].deliveryType, 
        customerTypeCode: selectRows.value[0].customerTypeCode,
        customerType: selectRows.value[0].customerType,
        storeType: selectRows.value[0].storeType,
        province: selectRows.value[0].province,
        city: selectRows.value[0].city,
        district: selectRows.value[0].district,

      });

      //门店等级
      customerLevel.value = selectRows.value[0].storeLevel;
    } finally {
    }
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}

/*update-begin-author:taoyan date:2022-7-27 for:modal评论区域样式*/
.jeecg-comment-outer {
  border-left: 1px solid #f0f0f0;

  .ant-tabs-nav-wrap {
    /*  text-align: center;*/
  }
}

.jeecg-modal-content {
  >.scroll-container {
    //update-begin---author:wangshuai---date:2023-12-05---for:【QQYUN-7297】表单讨论弹窗放大按钮时只显示一部分---
    padding: 6px;
    //update-end---author:wangshuai---date:2023-12-05---for:【QQYUN-7297】表单讨论弹窗放大按钮时只显示一部分---
  }
}

/*update-end-author:taoyan date:2022-7-27 for:modal评论区域样式*/

// wrapper设为100%，兼容之前写过的弹窗自定义样式
.jeecg-modal-wrapper,
.jeecg-modal-content {
  height: 100%;
}

html[data-theme='dark'] {
  .jeecg-comment-outer {
    border-left: 1px solid rgba(253, 253, 253, 0.12);
  }
}

.custom-red-cell {
  background-color: red !important;
}

</style>